const fs = require('fs')
const path = require('path')
const OSS = require('ali-oss')
const clientOss = new OSS({
  region: '',
  accessKeyId: '',
  accessKeySecret: '',
  bucket: '',
})

const uploadOss = async (file) => {
  return new Promise(async (resolve, reject) => {
    try {
      const { originalname, buffer } = file
      let name = new Date().getTime()
      fs.writeFileSync(
        path.join(__dirname, `./uploads/${name}-${originalname}`),
        buffer
      )
      await clientOss.put(
        `imgs/${name}-${originalname}`,
        path.join(__dirname, `./uploads/${name}-${originalname}`)
      )
      // 上传之后删除本地文件
      fs.unlinkSync(path.join(__dirname, `./uploads/${name}-${originalname}`))
      resolve(
        `https://wlmpro.oss-cn-beijing.aliyuncs.com/imgs/${name}-${originalname}`
      )
    } catch (err) {
      reject(err)
    }
  })
}

module.exports = uploadOss
